package com.tencent.sr.iris.activity.service.event.task;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.tencent.sr.iris.activity.common.enums.AwardRecordIssueStatusEnum;
import com.tencent.sr.iris.activity.common.enums.TaskBatchDateIsParticipatedEnum;
import com.tencent.sr.iris.activity.common.enums.TaskEstimateStatusEnum;
import com.tencent.sr.iris.activity.common.enums.UserTaskStatusEnum;
import com.tencent.sr.iris.activity.dependency.dto.data.CommissionInfoDTO;
import com.tencent.sr.iris.activity.domain.event.dto.ActivityDTO;
import com.tencent.sr.iris.activity.domain.event.dto.ActivityTaskDTO;
import com.tencent.sr.iris.activity.domain.event.dto.InviteLimitDTO;
import com.tencent.sr.iris.activity.interfaces.enums.ActivityEventTypeEnum;
import com.tencent.sr.iris.activity.interfaces.enums.ActivityIdEnum;
import com.tencent.sr.iris.activity.interfaces.enums.OrderStatusEnum;
import com.tencent.sr.iris.activity.interfaces.event.dto.ActivityEventDTO;
import com.tencent.sr.iris.activity.interfaces.message.DistributionOrderEvent;
import com.tencent.sr.iris.activity.interfaces.response.group.task.FirstOrderInfoRes;
import com.tencent.sr.iris.activity.repository.entity.TIrisActivityAwardRecordDO;
import com.tencent.sr.iris.activity.repository.entity.TIrisUserTaskRecordDO;
import com.tencent.sr.iris.activity.service.activity.ActivityCommonService;
import com.tencent.sr.iris.activity.service.activity.IrisActivityAwardRecordService;
import com.tencent.sr.iris.activity.service.activity.IrisUserTaskRecordService;
import com.tencent.sr.iris.activity.service.config.ActivityConfig;
import com.tencent.sr.iris.activity.service.config.ResponseMockConfig;
import com.tencent.sr.iris.activity.service.constant.ActivityRedisKey;
import com.tencent.sr.iris.activity.service.event.util.ActivityCommonUtilService;
import com.tencent.sr.iris.activity.service.event.vo.BaseUserTaskDataVO;
import com.tencent.sr.iris.activity.service.event.vo.TaskExecutorExtendInfo;
import com.tencent.sr.iris.activity.service.util.IdCreateorUtil;
import com.tencent.sr.iris.activity.service.util.LocalDateUtil;
import com.tencent.sr.rmall.common.exception.retail.TRetailBizException;
import com.tencent.sr.rmall.common.exception.retail.TRetailErrorException;
import com.tencent.sr.rmall.springbootstarter.utils.JsonUtils;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.BooleanUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class IrisInviteNewTaskExecutor extends AbstractIrisTaskExecutor{
    @Resource
    private ActivityCommonService activityCommonService;

    @Resource
    private IdCreateorUtil idCreateorUtil;

    @Resource
    private IrisUserTaskRecordService userTaskRecordService;

    @Resource
    private ActivityConfig activityConfig;

    @Resource
    private IrisActivityAwardRecordService awardRecordService;

    @Resource
    private RedissonClient redissonClient;

    @Resource
    private ResponseMockConfig responseMockConfig;

    @Resource
    private ActivityCommonUtilService activityCommonUtilService;

    /**
     * 分布式锁最大执行时间30秒
     */
    private static final  int MAX_LOCK_TIME = 30;

    /**
     * 重写
     * 邀请有礼活动,以成为见习会员时间做任务时间准入的校验
     *
     * @param eventDTO
     * @param act
     * @param task
     */
    @Override
    void before(ActivityEventDTO eventDTO, ActivityDTO act, ActivityTaskDTO task) {
        //查询成为见习时间
        Long becomeTraineeTime = activityCommonService.queryTraineeTime(eventDTO.getUid());
        if (becomeTraineeTime < task.getStartTime().getTime() || becomeTraineeTime > task.getEndTime().getTime()) {
            log.info("任务处理：用户成为见习会员时间不在任务时间范围内,不处理，eventIdempotent:{},traineeTime:{},taskId:{},taskTime:{}-{}",
                    eventDTO.getIdempotent(), becomeTraineeTime, task.getBizId(), task.getStartTime(),
                    task.getEndTime());
            throw new TRetailBizException("见习会员时间不在任务时间范围内，不处理");
        }
        if (becomeTraineeTime < activityCommonService.queryInviteUpperLimitChangeTime(eventDTO.getUid())){
            log.info("任务处理：用户成为见习会员时间在上限策略切换时间前,不处理，eventIdempotent:{},traineeTime:{},taskId:{},taskTime:{}-{}",
                    eventDTO.getIdempotent(), becomeTraineeTime, task.getBizId(), task.getStartTime(),
                    task.getEndTime());
            throw new TRetailBizException("见习会员时间在上限策略切换时间前，不处理");
        }
    }

    @Override
    public void fillTaskRecordStatus(ActivityEventDTO eventDTO, ActivityDTO act, ActivityTaskDTO task,
            TIrisUserTaskRecordDO userTaskRecordDO, LocalDate currentLocalDate) {

    }

    @SneakyThrows
    @Override
    public void process(ActivityEventDTO msg, ActivityDTO activity, ActivityTaskDTO task,
            List<String> eventHandingInfoList, TaskExecutorExtendInfo taskExecutorExtendInfo) {
        RLock lock = null;
        try{
            String lockKey = ActivityRedisKey.getInviteTaskNewLockKey(msg.getPid());
            lock = redissonClient.getLock(lockKey);
            if (!lock.tryLock(MAX_LOCK_TIME, TimeUnit.SECONDS)) {
                eventHandingInfoList.add("任务处理：获取分布式锁失败，当前上级邀请任务正在处理");
                log.info("任务处理：获取分布式锁失败，当前上级邀请任务正在处理,pid:{},uid:{},msgId:{}",
                        msg.getPid(),msg.getUid(),msg.getIdempotent());
                //抛个异常重试
                throw new TRetailErrorException("获取分布式锁失败");
            }
            //解析任务执行条件门槛值,区分测试
            addParameterForTask(task, msg);
            log.info("任务门槛值,commissionLimit={},shareTimeLimit={},msgId:{}", task.getCommissionLimit(),
                    task.getShareTimeLimit(), msg.getIdempotent());
            //查询任务完成进度
            TIrisUserTaskRecordDO userTaskRecordDO = queryUserTaskRecord(msg.getUid(), activity.getBizId(),
                    task.getBizId(), null);
            //已完成的不再更新进度
            if (Objects.nonNull(userTaskRecordDO)) {
                if (UserTaskStatusEnum.FINISHED.getCode() == userTaskRecordDO.getUserTaskStatus()) {
                    //已完成任务,不再更新进度
                    eventHandingInfoList.add("任务已完成,不再更新进度,userTaskRecordId=" + userTaskRecordDO.getBizId());
                    log.info("任务已完成,不再更新进度,userTaskRecordId={},msgId:{}", userTaskRecordDO.getBizId()
                            , msg.getIdempotent());
                    return;
                }
                if (UserTaskStatusEnum.UNFINISHED.getCode() == userTaskRecordDO.getUserTaskStatus()) {
                    //未完成任务,直接跳过
                    log.info("任务未完成,不再更新该任务进度,userTaskRecordId={}", userTaskRecordDO.getBizId());
                    eventHandingInfoList.add("任务未完成,不再更新该任务进度,userTaskRecordId=" + userTaskRecordDO.getBizId());
                    return;
                }
            } else {
                //查询成为见习时间
                Long becomeTraineeTime = activityCommonService.queryTraineeTime(msg.getUid());
                //新增用户活动任务完成进度
                userTaskRecordDO = buildUserTaskRecordDO(activity, task, msg, becomeTraineeTime);
            }
            ///查询佣金
            CommissionInfoDTO commissionInfoDTO = getCommissionInfo(msg.getUid(),
                    userTaskRecordDO.getCurrentTaskStartTime(), userTaskRecordDO.getCurrentTaskEndTime());
            //更新进度参数
            userTaskRecordDO.setEstimateCommission(commissionInfoDTO.getEstimateCommission());

            //任务周期结束时间 + 60天以后,计算是否达到门槛：
            //新增判断：T+60以后(不包含T+60天)，【分佣成功】+【订单交易完成且分佣未取消】是否达门槛（T为下单时间）
            int plusDays = activityConfig.getCommissionPlusDays(userTaskRecordDO.getUid());
            LocalDate taskEndDatePlus60 = userTaskRecordDO.getCurrentTaskEndTime().toInstant()
                    .atZone(ZoneId.systemDefault())
                    .toLocalDate().plusDays(plusDays);

            Integer commission = Objects.isNull(commissionInfoDTO.getCommission()) ? 0 : commissionInfoDTO.getCommission();
            LocalDate currentLocalDate = LocalDate.now();
            if (currentLocalDate.isAfter(taskEndDatePlus60)) {
                Integer waitCommissionAmt = Objects.isNull(commissionInfoDTO.getWaitCommissionAmt()) ? 0
                        : commissionInfoDTO.getWaitCommissionAmt();
                commission = commission + waitCommissionAmt;
            }
            userTaskRecordDO.setCommission(commission);
            userTaskRecordDO.setGmv(commissionInfoDTO.getGmv());

            userTaskRecordDO.setShareCount(commissionInfoDTO.getShareUvTo29());
            String extInfo = activityCommonUtilService.buildTaskRecordExtInfo(userTaskRecordDO.getExtInfo(), commissionInfoDTO);
            userTaskRecordDO.setExtInfo(extInfo);

            Long becomeTraineeTime = activityCommonService.queryTraineeTime(msg.getUid());
            //填充任务完成状态
            fillTaskRecordStatus(msg, task, userTaskRecordDO, taskExecutorExtendInfo, commissionInfoDTO);

            //查询成为见习时间
            //查询见习当月该上级是否达到发奖上限
            InviteLimitDTO inviteLimitDTO = queryInviteLimit(msg.getPid(), becomeTraineeTime);
            log.info("IrisInviteNewTaskExecutor查询上限结果，inviteLimitDTO:{},uid={},pid={},msgId:{}",
                    JSON.toJSONString(inviteLimitDTO), msg.getUid(), msg.getPid(), msg.getIdempotent());
            if (BooleanUtils.isFalse(inviteLimitDTO.isSatisfy())) {
                userTaskRecordDO.setIsParticipated(TaskBatchDateIsParticipatedEnum.LIMITED.getCode());
                eventHandingInfoList.add("邀请有礼任务发奖上限被限");
                //其他未完成的任务状态兜底处理
                if (BooleanUtils.isFalse(activityConfig.isHandleInviteTaskStatusStop())){
                    handleTaskStatus(userTaskRecordDO.getPid(),becomeTraineeTime,null);
                }
            }

            boolean finish = BooleanUtils.isTrue(UserTaskStatusEnum.FINISHED.getCode() == userTaskRecordDO.getUserTaskStatus());
            FirstOrderInfoRes firstOrderInfo = commissionInfoDTO.getFirstOrderInfo();
            if (firstOrderInfo != null) {
                long awardValue = Optional.ofNullable(firstOrderInfo.getPaymentAmount()).orElse(0L)
                        - Optional.ofNullable(firstOrderInfo.getCouponPrice()).orElse(0L);
                boolean awardValueNotValid = awardValue <= 0;
                if (finish && awardValueNotValid) {
                    //任务已完成，发奖金额为0，删除任务
                    userTaskRecordService.deleteTaskRecord(userTaskRecordDO);
                    log.info("任务已完成，发奖金额为0，删除任务，uid：{}，activityId：{}，taskId：{}，taskPeriod：{}", userTaskRecordDO.getUid(),
                            userTaskRecordDO.getActivityId(), userTaskRecordDO.getTaskId(), userTaskRecordDO.getTaskPeriod());
                    return;
                }
            }

            //任务进度更新
            TIrisActivityAwardRecordDO awardRecordDO = null;
            if (finish) {
                eventHandingInfoList.add("邀请有礼任务达成");
                log.info("邀请有礼任务达成,uid:{},commissionInfoDTO:{},msg:{}", msg.getUid(),
                        JSON.toJSONString(commissionInfoDTO), JSON.toJSONString(msg));
                log.info("IrisInviteNewTaskExecutor queryInviteLimit inviteLimitDTO:{}"
                        ,JSON.toJSONString(inviteLimitDTO));
                if (BooleanUtils.isTrue(inviteLimitDTO.isSatisfy())) {
                    //发放权益
                    awardRecordDO = activityCommonService.sendAwardForSupervisor(userTaskRecordDO, task);
                    //如果派奖成功或者失败派奖上限缓存递增
                    if (awardRecordDO.getIssueStatus() == AwardRecordIssueStatusEnum.ISSUE_SUCCEED.getCode()
                        || awardRecordDO.getIssueStatus() == AwardRecordIssueStatusEnum.ISSUE_FAILED.getCode()) {
                        awardRecordService.incrInviteAwardLimitCache(userTaskRecordDO.getPid()
                                ,userTaskRecordDO.getUid(),userTaskRecordDO.getBizId());
                    }
                    //当正好最后一个坑位被占的时候处理其他未完成的任务状态处理
                    Integer inviteLimit = inviteLimitDTO.getInviteLimit();
                    Integer inviteDevoteNum = inviteLimitDTO.getInviteDevoteNum();
                    if (Objects.nonNull(inviteLimit) && Objects.nonNull(inviteDevoteNum)
                            && (inviteLimit - inviteDevoteNum) <= 1){
                        //其他未完成的任务状态处理
                        handleTaskStatus(userTaskRecordDO.getPid(),becomeTraineeTime,awardRecordDO);
                    }

                }
            } else {
                eventHandingInfoList.add("邀请有礼任务未达成");
            }

            //更新用户活动任务完成进度
            userTaskRecordService.updateUserTaskRecordStatus(userTaskRecordDO, awardRecordDO);
        } finally {
            if (lock != null && lock.isLocked() && lock.isHeldByCurrentThread()) {
                lock.unlock();
            }
        }
    }

    private void handleTaskStatus(String pid, Long becomeTraineeTime, TIrisActivityAwardRecordDO awardRecordDO) {
        //查询邀请有礼在becomeTraineeTime所在月中任务状态为进行中或者受限状态的下级uid集合
        List<String> uidList = userTaskRecordService.queryInviteTaskRecordByPid(pid,
                new Date(becomeTraineeTime), Arrays.asList(UserTaskStatusEnum.PROGRESS.getCode(),
                        UserTaskStatusEnum.LIMITED.getCode()));
        //处理最后一个发奖坑位被占的时候，去设置其他进行中的任务进度为受限中状态，此时es有延迟，所以去掉最后一个发奖人的uid
        if (!CollectionUtils.isEmpty(uidList)
                && Objects.nonNull(awardRecordDO)
                && (awardRecordDO.getIssueStatus() == AwardRecordIssueStatusEnum.ISSUE_SUCCEED.getCode() ||
                awardRecordDO.getIssueStatus() == AwardRecordIssueStatusEnum.ISSUE_FAILED.getCode())){
            uidList.remove(awardRecordDO.getUid());
        }
        //设置IsParticipated状态为受限
        userTaskRecordService.updateUserTaskRecordIsParticipated(uidList,TaskBatchDateIsParticipatedEnum.LIMITED, null);
    }

    public CommissionInfoDTO getCommissionInfo(String uid, Date becomeTraineeTime, Date taskEndTime) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String startTime = sdf.format(becomeTraineeTime);
        String endTime = sdf.format(taskEndTime);

        boolean firstOrderAward = activityCommonUtilService.firstOrderAward(uid, becomeTraineeTime);
        return activityCommonService.queryInviteTaskTarget(uid, startTime, endTime, firstOrderAward);
    }

    private InviteLimitDTO queryInviteLimit(String pid,Long becomeTraineeTime) {
        InviteLimitDTO inviteLimitDTO = activityCommonService.queryInviteLimitByAward(pid, becomeTraineeTime);
        if (inviteLimitDTO.isError()) {
            log.error("查询邀请上限失败，pid：{}，inviteLimitDTO：{}", pid, JSON.toJSONString(inviteLimitDTO));
            throw new TRetailErrorException(inviteLimitDTO.getDesc()+"，查询邀请上限失败");
        }
        return inviteLimitDTO;
    }

    private void addParameterForTask(ActivityTaskDTO task, ActivityEventDTO msg) {
        task.parseLimitCondition();
    }

    public void fillTaskRecordStatus(ActivityEventDTO eventDTO, ActivityTaskDTO task, TIrisUserTaskRecordDO userTaskRecordDO,
                                     TaskExecutorExtendInfo taskExecutorExtendInfo, CommissionInfoDTO commissionInfoDTO) {
        String uid = userTaskRecordDO.getUid();

        LocalDate currentLocalDate = LocalDate.now();
        Date currentTaskStartTime = userTaskRecordDO.getCurrentTaskStartTime();

        boolean firstOrderAward = activityCommonUtilService.firstOrderAward(uid, currentTaskStartTime);
        if (firstOrderAward && Objects.equals(task.getActivityId(), ActivityIdEnum.INVITE_GIFT.getCode())) {
            fillFirstIOrderInfo(userTaskRecordDO, currentLocalDate, commissionInfoDTO);
            return;
        }

        LocalDate currentTaskStartDate = currentTaskStartTime.toInstant()
                .atZone(ZoneId.systemDefault())
                .toLocalDate();
        LocalDate currentTaskEndDate = userTaskRecordDO.getCurrentTaskEndTime().toInstant()
                .atZone(ZoneId.systemDefault())
                .toLocalDate();

        int plusDays = activityConfig.getCommissionPlusDays(uid);
        LocalDate currentTaskEndDatePlus60 = userTaskRecordDO.getCurrentTaskEndTime().toInstant()
                .atZone(ZoneId.systemDefault())
                .toLocalDate().plusDays(plusDays);
        Integer gmv = userTaskRecordDO.getGmv();

        boolean commissionSuccess = false;
        if (eventDTO.getEventType().equals(ActivityEventTypeEnum.DISTRIBUTION_ORDER.getCode())) {
            commissionSuccess = dealDistributionOrderEvent(eventDTO, currentTaskStartDate, currentTaskEndDate, userTaskRecordDO);
        }
        //在任务周期内
        if (LocalDateUtil.isLocalDateBetween(currentLocalDate, currentTaskStartDate, currentTaskEndDate)) {
            //设置有效gmv任务完成状态
            if (gmv > task.getGmv()) {
                userTaskRecordDO.setEstimateUserTaskStatus(UserTaskStatusEnum.FINISHED.getCode());
            } else {
                userTaskRecordDO.setEstimateUserTaskStatus(UserTaskStatusEnum.PROGRESS.getCode());
            }
            //实际佣金条件判断
            if (commissionSuccess) {
                //是否需要判断gmv
                if (Objects.nonNull(taskExecutorExtendInfo)
                        && BooleanUtils.isTrue(taskExecutorExtendInfo.isInviteGiftCheckGmv())) {
                    if (gmv > 0) {
                        userTaskRecordDO.setUserTaskStatus(UserTaskStatusEnum.FINISHED.getCode());
                        userTaskRecordDO.setEstimateUserTaskStatus(UserTaskStatusEnum.FINISHED.getCode());
                    } else {
                        userTaskRecordDO.setUserTaskStatus(UserTaskStatusEnum.PROGRESS.getCode());
                    }
                } else {
                    userTaskRecordDO.setUserTaskStatus(UserTaskStatusEnum.FINISHED.getCode());
                    userTaskRecordDO.setEstimateUserTaskStatus(UserTaskStatusEnum.FINISHED.getCode());
                }
            } else {
                userTaskRecordDO.setUserTaskStatus(UserTaskStatusEnum.PROGRESS.getCode());
            }
            //在任务周期结束后60天内
        } else if (currentLocalDate.isAfter(currentTaskEndDate)
                && (currentLocalDate.equals(currentTaskEndDatePlus60) || currentLocalDate
                .isBefore(currentTaskEndDatePlus60))) {
            //设置有效gmv任务完成状态
            LocalDate endDatePlusOne = currentTaskEndDate.plusDays(1);
            if (gmv > task.getGmv()) {
                userTaskRecordDO.setEstimateUserTaskStatus(UserTaskStatusEnum.FINISHED.getCode());
            } else if (currentLocalDate.isAfter(endDatePlusOne)) {
                //有效gmv没达成，且已过任务结束时间24小时，直接判断为未完成
                userTaskRecordDO.setEstimateUserTaskStatus(UserTaskStatusEnum.UNFINISHED.getCode());
                userTaskRecordDO.setUserTaskStatus(UserTaskStatusEnum.UNFINISHED.getCode());
                return;
            }
            //实际佣金条件判断
            if (commissionSuccess) {
                //是否需要判断gmv
                if (Objects.nonNull(taskExecutorExtendInfo)
                        && BooleanUtils.isTrue(taskExecutorExtendInfo.isInviteGiftCheckGmv())) {
                    if (gmv > 0) {
                        userTaskRecordDO.setUserTaskStatus(UserTaskStatusEnum.FINISHED.getCode());
                        userTaskRecordDO.setEstimateUserTaskStatus(UserTaskStatusEnum.FINISHED.getCode());
                    } else {
                        userTaskRecordDO.setUserTaskStatus(UserTaskStatusEnum.PROGRESS.getCode());
                    }
                } else {
                    userTaskRecordDO.setUserTaskStatus(UserTaskStatusEnum.FINISHED.getCode());
                    userTaskRecordDO.setEstimateUserTaskStatus(UserTaskStatusEnum.FINISHED.getCode());
                }
            } else {
                userTaskRecordDO.setUserTaskStatus(UserTaskStatusEnum.PROGRESS.getCode());
            }
            //任务周期结束60天后
        } else if (currentLocalDate.isAfter(currentTaskEndDatePlus60)) {
            userTaskRecordDO.setUserTaskStatus(UserTaskStatusEnum.UNFINISHED.getCode());
            userTaskRecordDO.setEstimateUserTaskStatus(UserTaskStatusEnum.UNFINISHED.getCode());
        }
    }

    /**
     * 邀请有礼首单发奖任务状态
     * @param userTaskRecordDO
     * @param currentLocalDate
     * @param commissionInfoDTO
     */
    private void fillFirstIOrderInfo(TIrisUserTaskRecordDO userTaskRecordDO, LocalDate currentLocalDate, CommissionInfoDTO commissionInfoDTO) {
        FirstOrderInfoRes firstOrderInfo = Optional.ofNullable(commissionInfoDTO.getFirstOrderInfo()).orElseGet(FirstOrderInfoRes::new);
        String orderStatus = firstOrderInfo.getOrderStatus();
        boolean sent = Objects.equals(OrderStatusEnum.SENT.getCode(), orderStatus);
        boolean success = Objects.equals(OrderStatusEnum.SUCCESS.getCode(), orderStatus);
        boolean deliverPending = Objects.equals(OrderStatusEnum.DELIVER_PENDING.getCode(), orderStatus);

        String uid = userTaskRecordDO.getUid();
        int plusDays = activityConfig.getCommissionPlusDays(uid);
        LocalDate currentTaskEndDatePlus60 = userTaskRecordDO.getCurrentTaskEndTime().toInstant()
                .atZone(ZoneId.systemDefault())
                .toLocalDate().plusDays(plusDays);

        Date currentTaskStartTime = userTaskRecordDO.getCurrentTaskStartTime();
        LocalDate currentTaskStartDate = currentTaskStartTime.toInstant()
                .atZone(ZoneId.systemDefault())
                .toLocalDate();
        LocalDate currentTaskEndDate = userTaskRecordDO.getCurrentTaskEndTime().toInstant()
                .atZone(ZoneId.systemDefault())
                .toLocalDate();

        //应发奖励金
        Long couponPrice = Optional.ofNullable(firstOrderInfo.getCouponPrice()).orElse(0L);
        Long paymentAmount = Optional.ofNullable(firstOrderInfo.getPaymentAmount()).orElse(0L);
        int payValue = Math.toIntExact(paymentAmount - couponPrice);
        int sendValue = Math.max(payValue, 0);
        userTaskRecordDO.setSendAward(sendValue);

        //设置订单完成时间
        Long finishTime = firstOrderInfo.getFinishTime();
        if (success && finishTime!= null) {
            userTaskRecordDO.setOrderFinishTime(DateUtil.date(finishTime));
        }
        //周期内
        if (LocalDateUtil.isLocalDateBetween(currentLocalDate, currentTaskStartDate, currentTaskEndDate)) {
            //预估状态
            if (success || sent || deliverPending) {
                userTaskRecordDO.setEstimateUserTaskStatus(TaskEstimateStatusEnum.FINISHED.getCode());
            } else {
                userTaskRecordDO.setEstimateUserTaskStatus(TaskEstimateStatusEnum.PROGRESS.getCode());
            }
            //实际状态
            if (success) {
                userTaskRecordDO.setUserTaskStatus(UserTaskStatusEnum.FINISHED.getCode());
            } else {
                userTaskRecordDO.setUserTaskStatus(UserTaskStatusEnum.PROGRESS.getCode());
            }
        } else if (currentLocalDate.isAfter(currentTaskEndDate)
                && (currentLocalDate.equals(currentTaskEndDatePlus60) || currentLocalDate
                .isBefore(currentTaskEndDatePlus60))) {
            //周期结束-T+60
            LocalDate endDatePlusOne = currentTaskEndDate.plusDays(1);
            if (success) {
                userTaskRecordDO.setEstimateUserTaskStatus(TaskEstimateStatusEnum.FINISHED.getCode());
                userTaskRecordDO.setUserTaskStatus(UserTaskStatusEnum.FINISHED.getCode());
            } else if (sent || deliverPending) {
                userTaskRecordDO.setEstimateUserTaskStatus(TaskEstimateStatusEnum.FINISHED.getCode());
                userTaskRecordDO.setUserTaskStatus(UserTaskStatusEnum.PROGRESS.getCode());
            } else if (currentLocalDate.isAfter(endDatePlusOne)) {
                //首单没达成，且已过任务结束时间24小时，直接判断为未完成
                userTaskRecordDO.setEstimateUserTaskStatus(TaskEstimateStatusEnum.UNFINISHED.getCode());
                userTaskRecordDO.setUserTaskStatus(UserTaskStatusEnum.UNFINISHED.getCode());
            }
        } else if (currentLocalDate.isAfter(currentTaskEndDatePlus60)) {
            //T+60后
            if (success) {
                userTaskRecordDO.setUserTaskStatus(UserTaskStatusEnum.FINISHED.getCode());
                userTaskRecordDO.setEstimateUserTaskStatus(TaskEstimateStatusEnum.FINISHED.getCode());
            } else {
                userTaskRecordDO.setUserTaskStatus(UserTaskStatusEnum.UNFINISHED.getCode());
                userTaskRecordDO.setEstimateUserTaskStatus(TaskEstimateStatusEnum.UNFINISHED.getCode());
            }
        }
    }

    private boolean dealDistributionOrderEvent(ActivityEventDTO eventDTO,LocalDate currentTaskStartDate
            ,LocalDate currentTaskEndDate,TIrisUserTaskRecordDO userTaskRecordDO) {
        boolean result = false;
        String eventInfo = eventDTO.getEventInfo();
        DistributionOrderEvent event = JsonUtils.parse(eventInfo,
                DistributionOrderEvent.class);
        //查询是否走mock分销单数据
        DistributionOrderEvent mockDTO = responseMockConfig.getMockDistributionOrderEvent(eventDTO.getUid());
        if (mockDTO != null) {
            log.info("dealDistributionOrderEvent命中mock数据白名单，直接返回mock数据，uid:{}，mockDTO:{},eventDTO:{}"
                    , eventDTO.getUid(), JSON.toJSONString(mockDTO),JSON.toJSONString(eventDTO));
            event =  mockDTO;
        }
        String commissionStatus = event.getCommissionStatus();
        String orderStatus = event.getOrderStatus();
        Long gmv = event.getGmv();
        Long orderCreateTime = event.getOrderCreateTime();
        Long finishTime = event.getFinishTime();

        //订单消息的gmv必须大于0才算是交易完成
        if (orderStatus.equals(OrderStatusEnum.SUCCESS.getCode()) &&
                Objects.nonNull(finishTime) && gmv > 0) {
            LocalDate localDate = new Date(orderCreateTime).toInstant()
                    .atZone(ZoneId.systemDefault())
                    .toLocalDate();
            if (LocalDateUtil.isLocalDateBetween(localDate, currentTaskStartDate, currentTaskEndDate)) {
                if (Objects.isNull(userTaskRecordDO.getOrderFinishTime())){
                    userTaskRecordDO.setOrderFinishTime(new Date(finishTime));
                }
                result = true;
            }
        }
        log.info("分佣单消息处理结果,commissionStatus:{},orderStatus:{},gmv:{},finishTime:{},result:{},uid:{}",
                commissionStatus,orderStatus,gmv,finishTime,result,eventDTO.getUid());
        return result;
    }

    @Override
    public boolean executeAward(ActivityEventDTO event, ActivityDTO act, ActivityTaskDTO task) {
        return false;
    }

    @Override
    public boolean checkTaskThreshold(ActivityEventDTO event, ActivityDTO act, ActivityTaskDTO task,
            BaseUserTaskDataVO userTaskDataVO) {
        return false;
    }

    @Override
    public BaseUserTaskDataVO prepareUserTaskData(ActivityEventDTO event, ActivityDTO act, ActivityTaskDTO task) {
        return null;
    }

    private TIrisUserTaskRecordDO buildUserTaskRecordDO(ActivityDTO activity, ActivityTaskDTO taskDTO,
            ActivityEventDTO msg, Long becomeTraineeTime) {
        TIrisUserTaskRecordDO userTaskRecordDO = new TIrisUserTaskRecordDO();
        userTaskRecordDO.setBizId(idCreateorUtil.genId());
        userTaskRecordDO.setUid(msg.getUid());
        userTaskRecordDO.setPid(msg.getPid());
        userTaskRecordDO.setActivityId(activity.getBizId());
        userTaskRecordDO.setTaskId(taskDTO.getBizId());
        userTaskRecordDO.setActivityType(activity.getActivityType());
        userTaskRecordDO.setPeriodType(activity.getPeriodType());
        userTaskRecordDO.setUserTaskStatus(UserTaskStatusEnum.PROGRESS.getCode());
        userTaskRecordDO.setEstimateUserTaskStatus(UserTaskStatusEnum.PROGRESS.getCode());
        //任务结束时间
        //Date taskEndTime = getTaskEndTime(taskDTO, becomeTraineeTime);
        userTaskRecordDO.setCurrentTaskStartTime(initCurrentTaskStartTime(becomeTraineeTime));
        userTaskRecordDO.setCurrentTaskEndTime(initCurrentTaskEndTime(becomeTraineeTime));
        userTaskRecordDO.setTier(taskDTO.getTier());
        userTaskRecordService.saveUserTaskRecord(userTaskRecordDO);
        return userTaskRecordDO;
    }

    public Date initCurrentTaskStartTime(Long becomeTraineeTime) {
        return new Date(becomeTraineeTime);
    }

    public Date initCurrentTaskEndTime(Long becomeTraineeTime) {
        return TraineeTimeTo29(becomeTraineeTime);
    }
}
